package com.lagou.handler;

import com.lagou.service.IUserService;
import com.lagou.service.UserServiceImpl;
import com.lagou.util.ApplicationContextUtil;
import com.lagou.util.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //从解码器种拿出解析出来的RpcRequest对象，依靠反射去调用方法
        RpcRequest rpcRequest = (RpcRequest) msg;
        String className = rpcRequest.getClassName();
        String methodName = rpcRequest.getMethodName();
        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object[] paramters = rpcRequest.getParamters();
        Class<?> aClass = Class.forName(className);
        //从spring的ioc容器中拿出这个对象  在这里是UserServiceImpl类。
        Object bean = ApplicationContextUtil.getBean(aClass);
        Method method = aClass.getMethod(methodName,parameterTypes);
        String result = (String)method.invoke(bean, paramters);
        System.out.println("服务端调用方法，输出结果为"+result);
        ctx.writeAndFlush("success");
    }
}
